#pragma once

#include "Util.hpp"
#include "LogMessage.hpp"
#include "LogLevel.hpp"
#include <sstream>
#include <assert.h>
// 格式化子项类:从日志消息中取出指定的元素,追加到一块内存空间中去
#include <vector>
namespace log
{
    // 格式化子项基类
    class FormatItem
    {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        // 将日志的属性格式化到out空间后
        virtual void Format(std::ostream &out, LogMessage &Msg) = 0;
    };
    class MsgFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, LogMessage &Msg)
        {
            out << Msg._payload;
        }
    };
    class LevelFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, LogMessage &Msg)
        {
            out << LogLevel::LevelTo_String(Msg._level);
        }
    };
    class TimeFormatItem : public FormatItem
    {
    public:
        TimeFormatItem(const std::string &time_fmt = "%H:%M:%S") : _time_fmt(time_fmt)
        {
        }
        void Format(std::ostream &out, LogMessage &Msg)
        {
            struct tm t;
            localtime_r(&Msg._ctime, &t); // 将时间戳转化为对应我们日常的时间并且存储在t结构体里面
            char tmp[128] = {0};
            strftime(tmp, 127, _time_fmt.c_str(), &t); // 将结构体里面存储的时间转化为_time_fmt形式的字符串并且存入到tmp中
            out << tmp;
        }

    private:
        std::string _time_fmt;
    };

    class FileFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, LogMessage &Msg)
        {
            out << Msg._file;
        }
    };
    class LineFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, LogMessage &Msg)
        {
            out << Msg._line;
        }
    };
    class LoggerFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, LogMessage &Msg)
        {
            out << Msg._logger;
        }
    };
    class ThreadFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, LogMessage &Msg)
        {
            out << Msg._id;
        }
    };
    class TabFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, LogMessage &Msg)
        {
            out << "\t";
        }
    };
    class NLineFormatItem : public FormatItem
    {
    public:
        void Format(std::ostream &out, LogMessage &Msg)
        {
            out << "\n";
        }
    };
    class OtherFormatItem : public FormatItem
    {
    public:
        OtherFormatItem(const std::string &str = "") : _str(str)
        {
        }
        void Format(std::ostream &out, LogMessage &Msg)
        {
            out << _str;
        }

    private:
        std::string _str;
    };

    // 格式化类
    class Formatter
    {
        /*
            %d ⽇期
            %T 缩进
            %t 线程id
            %p ⽇志级别
            %c ⽇志器名称
            %f ⽂件名
            %l ⾏号
            %m ⽇志消息
            %n 换⾏
         */
    public:
        using ptr=std::shared_ptr<Formatter>;
        Formatter(const std::string pattern = "[%d{%H:%M:%S}][%t][%p][%c][%f:%l]%T%m%n") : _pattern(pattern)
        {
            assert(PharsePattern());
        }

        // 将日志按照指定的格式转化成为相应的字符串
        void Format(std::ostream &os, LogMessage &Msg)
        {
            for (auto &item : _VFormatItem)
            {
                item->Format(os, Msg);
            }
        }
        std::string Format(LogMessage &Msg)
        {
            std::stringstream ss;
            Format(ss, Msg);
            return ss.str();
        }
        private:
        bool PharsePattern() // 解析格式字符串
        {
            size_t pos = 0;
            std::vector<std::pair<std::string, std::string>> fmt_vector; // 用来保存格式化字符与子格式的关系
            std::string key, val;
            while (pos < _pattern.size())
            {

                // 1.处理非格式化字符
                if (_pattern[pos] != '%')
                {
                    val.push_back(_pattern[pos++]);
                    continue;
                }
                // 如果是两个%相连的
                if (pos + 1 < _pattern.size() && _pattern[pos + 1] == '%')
                {
                    val.push_back('%');
                    pos += 2;
                    continue;
                }
                // 不为空添加到fmt_vector中
                if (val.empty() == false)
                {
                    fmt_vector.push_back(std::make_pair("", val));
                    val.clear();
                }

                // 说明%后面是格式化字符
                pos++; // 到达格式化字符的位置
                if (pos == _pattern.size())
                {
                    std::cout << "%后面未有对应的格式化字符" << std::endl;
                    return false;
                }
                key = _pattern[pos];
                pos++; // 到达格式化字符后面
                if (pos < _pattern.size() && _pattern[pos] == '{')
                {
                    pos += 1;
                    while (pos < _pattern.size() && _pattern[pos] != '}')
                    {
                        val.push_back(_pattern[pos++]);
                    }
                    if (pos == _pattern.size())
                    {
                        // 未找到'}',说明解析失败
                        std::cout << "未找到},格式解析失败" << std::endl;
                        return false;
                    }
                    pos++; // pos指向'}'走到新位置
                }
                fmt_vector.push_back(std::make_pair(key, val));
                key.clear();
                val.clear();
            }
            if (val.empty() == false)
            {
                fmt_vector.push_back(std::make_pair(key, val));
                key.clear();
                val.clear();
            }
            for (auto &it : fmt_vector)
            {
                _VFormatItem.push_back(CreateItem(it.first, it.second));
            }
            return true;
        }
        private:
        FormatItem::ptr CreateItem(const std::string &key, const std::string val) // 根据指定格式,创建格式化子项
        {
            if (key == "d")
                return std::make_shared<TimeFormatItem>(val);
            if (key == "t")
                return std::make_shared<ThreadFormatItem>();
            if (key == "p")
                return std::make_shared<LevelFormatItem>();
            if (key == "c")
                return std::make_shared<LoggerFormatItem>();
            if (key == "f")
                return std::make_shared<FileFormatItem>();
            if (key == "l")
                return std::make_shared<LineFormatItem>();
            if (key == "m")
                return std::make_shared<MsgFormatItem>();
            if (key == "n")
                return std::make_shared<NLineFormatItem>();
            if (key == "T")
                return std::make_shared<TabFormatItem>();
            if(key=="")
                return std::make_shared<OtherFormatItem>(val);
                std::cout<<"不是格式化字符:%"<<key<<std::endl;
                abort();
        }

    private:
        std::string _pattern; // 日志格式字符串
        std::vector<FormatItem::ptr> _VFormatItem;
    };

}